package vn.smartoffice.promail.controller.dialog;

import java.util.HashMap;
import java.util.Map;

import lombok.Getter;

import org.springframework.dao.DuplicateKeyException;
import org.zkoss.bind.BindUtils;
import org.zkoss.bind.annotation.AfterCompose;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.ContextParam;
import org.zkoss.bind.annotation.ContextType;
import org.zkoss.bind.annotation.ExecutionArgParam;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.select.Selectors;
import org.zkoss.zk.ui.select.annotation.VariableResolver;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zkplus.spring.DelegatingVariableResolver;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

import vn.smartoffice.auth.UserService;
import vn.smartoffice.promail.entity.MailAccount;
import vn.smartoffice.promail.services.MailAccountService;
import vn.smartoffice.promail.services.MailFolderService;
import vn.smartoffice.utils.DialogUtils;

@VariableResolver(DelegatingVariableResolver.class)
public class AccountDialogCtr {

	@WireVariable private MailAccountService mailAccountService;
	@WireVariable private MailFolderService mailFolderService;
	@WireVariable private UserService userService;

	@Getter private MailAccount selectedAccount;

	@Wire private Window accountDialog;

	@AfterCompose
	public void afterCompose(@ContextParam(ContextType.VIEW) Component view,
			@ExecutionArgParam("maiAccount") MailAccount selectedAccount) {
		Selectors.wireComponents(view, this, false);
		this.selectedAccount = selectedAccount;
	}

	@Command("save")
	public void save() {
		try {
			if (selectedAccount.getId() == null) {
				mailAccountService.save(selectedAccount);
				DialogUtils.showNotification("account.updateMessages");
			} else {
				mailAccountService.update(selectedAccount);
				DialogUtils.showNotification("account.updateMessages");
			}
			Map<String, Object> dataArgs = new HashMap<>();
			dataArgs.put("accountId", selectedAccount);
			accountDialog.detach();
			BindUtils.postGlobalCommand(null, null, "refreshMailAccount", dataArgs);
		} catch (Exception ex) {
			if (ex instanceof DuplicateKeyException) {
				Messagebox.show(Labels.getLabel("account.nameExits.errorMessages"), Labels.getLabel("wraning.title"),
						Messagebox.OK, Messagebox.EXCLAMATION);
			} else {
				throw ex;
			}
		}
	}

	@Command("cancel")
	public void cancel() {
		accountDialog.detach();
	}
}
